<template>
  <div class="common-layout">
    <el-container>
      <!-- 网页头导航 -->
      <el-header class="common-header" style="box-shadow:var(--el-box-shadow-light);">
        <AllHead></AllHead>
      </el-header>
      <el-container>
        <el-aside width="10vw">
          <!-- 列出食谱类型 -->
          <ul>
            <li v-for="(c, index) in cuisines"><el-button round
                :class="show[index] ? 'clickButton navButton' : 'navButton '" @click="choseFood(c.id, index)">{{
                  c.name
                }}</el-button>
            </li>
          </ul>
        </el-aside>

        <el-main>
         <!-- 展示食谱 -->
          <ul v-infinite-scroll="getScroll" infinite-scroll-distance="50" style="height: 90vh;">
            <li v-for="r in recipes" :key="r.id">
              
              <div class="big">
                <div class="box" @click="turnShow(r.id)">
                  <el-image :src="r.author.avatarUrl" class="img"></el-image>
                </div>
                <div class="text">
                  <div class="one" @click="turnShow(r.id)">{{ r.name }}</div>
                  <div class="author">
                    <el-link underline="never" @click="turnUserCerter(r.author.id)"><el-image :src="r.author.avatarUrl"
                        class="ReUserImg"></el-image>
                      <span class="nickname">{{ r.author.nickname }}</span></el-link><br>
                  </div>
                  <div class="icon">

                    <div class="smallIcon">
                      <!-- <iconify-icon icon="material-symbols:favorite-outline" class="red" @click="likeRecipe" /> -->
                      <iconify-icon icon="material-symbols:favorite-rounded" style="color: #fd040a" />
                      <span>{{ r.likeCount }}</span>
                    </div>
                    <div class="smallIcon">
                      <el-icon>
                        <ChatLineRound />
                      </el-icon>
                      <span>{{ r.commentCount }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </li>
          </ul>
          <!-- </el-scrollbar> -->
        </el-main>

      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { Picture as IconPicture, Lightning } from '@element-plus/icons-vue'
import { useWebSocketStore } from '@/stores/websocket'

import { useRouter } from 'vue-router';
import { useRoute } from 'vue-router';
import AllHead from './AllHead.vue';
const router = useRouter()
import axios from 'axios'
import { reactive, ref, nextTick, toRefs, onMounted } from 'vue'
import { useCheckStore } from '@/stores/counter';
import { storeToRefs } from 'pinia';
import Cookies from 'js-cookie'




// 获取webSocketStore
const wsStrore = useWebSocketStore()

// 食谱类型对象参数接口
interface cuisine {
  description: string
  id: number
  name: string
  recipeCount: number
  updateTime: string
}
let cuisines: cuisine[] = reactive([])
//得到食谱类型与百谱园数据（数组），给页面遍历
cuiList()
async function cuiList() {
  const List = await axios({
    url: '/api/board/queryBoardList',
  })
  Object.assign(cuisines, List.data.data)
  //默认展示百谱园
  await axios({
    url: '/api/recipe/getRecipeList',
    params: {
      limit: 40,
      offset: 0,
      boardId: BorderId.value,
    },
    headers: { 'Content-Type': 'application/json' }
  }).then(res => {
    recipes.length = 0
    Object.assign(recipes, res.data.data)
    console.log(recipes);
  })
}


// 展示食谱详细对象接口
interface author {
  avatarUrl: string
  id: number
  isAdmin: string
  nickname: string
}
interface recipe {
  author: author
  boardId: number
  collectCount: number
  commentCount: number
  coverImage: string
  difficulty: string
  id: number
  likeCount: number
  name: string
  servings: string
  userId: number
}
let recipes: recipe[] = reactive([])
let addTen: number = 10
let BorderId = ref(1)//板块类型id,目前默认的百谱园为id：11
// 当食谱滚动条展示到底时，自动执行函数getScroll(),从后端那新的数据增加新的食谱
const getScroll = () => {
  if(recipes.length<40){
    return
  }
  axios({
    url: '/api/recipe/getRecipeList',
    params: {
      limit: 40 + addTen,
      offset: 0,
      boardId: BorderId.value,
    },
    headers: { 'Content-Type': 'application/json' }
  }).then(async res => {
    addTen = addTen + 10//加十是为了不断拿到新的数据
    recipes.length = 0//拿数据需要先将食谱数组置为空，在赋值
    Object.assign(recipes, res.data.data)
  })
}

// 选择食谱类型
let show = ref(new Array(10).fill(false))
async function choseFood(id: number, index: number) {
  console.log(id);
  show.value.fill(false)
  show.value[index] = true
  console.log(show);

  BorderId.value = id//点击后修改板块id值

  await axios({
    url: '/api/recipe/getRecipeList',
    params: {
      limit: 40,//默认拿四十个数据
      offset: 0,
      boardId: id,
    },
    headers: { 'Content-Type': 'application/json' }

  }).then(res => {
    recipes.length = 0
    Object.assign(recipes, res.data.data)
  })
}

// 测试数组对象存储
let arr = reactive([
  { id: 0, msg: '123' },
  { id: 1, msg: '123' },
  { id: 2, msg: '123' },
  { id: 3, msg: '123' },
])
localStorage.setItem('MSG', JSON.stringify(arr))
console.log(localStorage.getItem('MSG'));
let arr1 = JSON.parse(localStorage.getItem('MSG') + '')
console.log(arr1);


let userId: number
// 通过接口拿到登录用户的id
axios({
  url: '/api/user/getPartUserInfo',
}).then(res => {
  sessionStorage.setItem('userId', res.data.data.id)//将userID存入本地中以便拿去
  userId = res.data.data.id
})


// 跳转至食谱作者用户中心，如果是登录用户本身则跳转至自己的用户中心
function turnUserCerter(authorID: number) {
  console.log(authorID, userId);
  if (authorID == userId) {
    router.push({
      path: '/usercenter'
    })
  } else {
    router.push({
      path: '/othercenter',
      query: { au: authorID }
    })
  }
}
// 跳转至食谱路由
function turnShow(id: number) {
  router.push({
    path: '/showrecipe',
    query: { recipeId: id }
  })
}





const messages = ref([])
const newMessage = ref('')
const messagesRef = ref(null)







// 判断是否连接
console.log(!wsStrore.isConnected);
// 获取webSocketStore
// const wsStrore = useWebSocketStore()
let gt = Cookies.get('checkLian')
// console.log(ic);
if(gt == null){
  wsStrore.connect('/ws/sendMessage')
  Cookies.set('checkLian','1')
  gt = Cookies.get('checkLian')
  // 监听WebSocket连接状态变化
  const checkConnection = setInterval(() => {
  if (!wsStrore.isConnected) {
    // WebSocket连接断开时跳转到登录页
    axios({
        url: '/api/user/logout',
        method: 'post'
    })
    router.push({
        path: '/login'
    })
    alert('你的账号在别处登录,怎么又来')
  }
  clearInterval(checkConnection)

}, 1000) // 每秒检查一次连接状态
}


const wsStore = useWebSocketStore()
async function getUnCheckNum(){
  let numAxios = axios({
    url:'/api/message/getUncheckNum'
  })
  wsStore.unCheckNum = (await numAxios).data.data
console.log('未读消息数'+wsStore.unCheckNum);

}
getUnCheckNum()


// 展示页面点赞方法，以后再做
// let likeMessage = reactive({
//   id: 5,
//   isLiked: 0,
//   recipeId: 6,
//   userId: 4
// })
// function likeRecipe() {
//   axios({
//     url: '/api/like/thumbsUpRecipe',
//     method: 'post',
//     data: JSON.stringify(likeMessage),
//     headers: { 'Content-Type': 'application/json' }
//   })
// }
// axios({
//   url: '/api/like/getLikeRecipeRecord',
//   params: {
//     recipeId: 7
//   },
//   headers: { 'content-type': 'application/x-www-form-urlencoded' }

// }).then(res => {
//   console.log();
// })

</script>

<style scoped>
.common-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #FFF9F0;
  background-image: linear-gradient(to bottom, #FFFCF5, #FFF9F0);
}

.common-header {
  z-index: 999;
  height: 10vh;
  /* background-color: rgb(213, 248, 201); */
  /* background-image: url('/src/views/Main/v2-63b8748368f6d6a43cd64cadab5c48aa_r.jpg'); */
  /* background-size: 100% 100%; */
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
}

.el-container {
  flex: 1;
  display: flex;
}

.common-layout::-webkit-scrollbar {
  display: none;
}

.el-aside {
  /* margin-top: 10vh; */
  width: 15vw;
  /* background-color: rgb(190, 231, 214); */
}

.el-main {
  /* margin-top: 10vh; */
  padding: 0px;
}

.navButton {
  background-color: white;
  width: 12vw;
  height: 8vh;
  margin-top: 1vh;
  margin-left: 0;
  border: none;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  font-weight: 500;
  color: #333;
}

.clickButton {
  background-color: #FFE8CC;

}

.navButton:hover {
  background-color: #FFE8CC;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.navButton:active {
  transform: translateY(0);
}

ul {
  margin: 0;
  padding: 0;
}

ul li {
  display: inline-block;
  list-style: none;
}

.big {
  height: 320px;
  width: 220px;
  background-color: white;
  margin: 20px;
  padding: 16px;
  border-radius: 2vw;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.big:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.box {
  cursor: pointer;
  height: 200px;
  width: 100%;
  position: relative;
  overflow: hidden;
  border-radius: 8px;
}

.img {
  height: 100%;
  width: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.box:hover .img {
  transform: scale(1.05);
}



.one {
  width: 200px;
  height: 60px;
  cursor: pointer;
  display: -webkit-box;
  overflow: hidden;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  text-overflow: ellipsis;
  word-break: break-all;

}

.one:hover {
  color: #FF8C42
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}

.ReUserImg {
  float: left;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #f0f0f0;
  margin-right: 6px;
}

.author {
  margin-bottom: 5px;
}

.author:hover .nickname {
  color: #FF8C42;
}

.nickname {
  width: 140px;
  margin-left: 5px;
  float: left;
  font-size: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.icon {
  position: relative;
  /* margin-right: 30px; */
  font-size: 13px;
}

.smallIcon {
  display: inline-block;
  width: 60px;
}
</style>
